
/*
楼层编辑
*/

var floorManagementid=sessionStorage.getItem("floorManagementid")
var floorManagementname=sessionStorage.getItem("floorManagementname")
var primaryClassification=[]//一级分类信息
var secondaryClassification=[]//二级分类信息
var fullPaths=""//上传图片信息
var imgoperation=false
findFloorCategoryMsg()
function findFloorCategoryMsg() {
    $.ajax({
        url:root.sroreinter.findFloorCategoryMsg,
        cache: false,  //禁用缓存
        type: "POST",
        async:false,//优先运行
        dataType:'json',
        data: {
            "floorId":floorManagementid,
        },
        success: function (data) {
            console.log(data)
            $("#pcUrl").attr("src",data.data.floorUrl)
            var oneCategoryListarr={}
            if(data.data.oneCategoryList!=null){
                var oneCategoryLists=data.data.oneCategoryList
                for (var i=0;i<oneCategoryLists.length;i++){
                    oneCategoryListarr={
                        "categoryId":oneCategoryLists[i].categoryId,
                        "floorId":oneCategoryLists[i].floorId,
                        "categoryLevel":oneCategoryLists[i].categoryLevel,
                        "categoryName":oneCategoryLists[i].categoryName
                    }
                    primaryClassification.push(oneCategoryListarr)

                }
            }
            var twoCategoryListarr={}
            if(data.data.twoCategoryList!=null){
                var twoCategoryLists=data.data.twoCategoryList
                for (var i=0;i<twoCategoryLists.length;i++){
                    twoCategoryListarr={
                        "categoryId":twoCategoryLists[i].categoryId,
                        "floorId":twoCategoryLists[i].floorId,
                        "categoryLevel":twoCategoryLists[i].categoryLevel,
                        "categoryName":twoCategoryLists[i].categoryName
                    }
                    secondaryClassification.push(twoCategoryListarr)

                }
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//一级
goods_listCategory1(1);
function goods_listCategory1(classNum) {
    var primaryClassificationall=[]
    var user_data = {
        category_level: classNum
    }
    var succCallBack = function (data, status, response) {
        if (data.data.length == 0) {
            $("#classSet1").append('<li class="clearfix pl-10 mb-5"  style="width: 95%" >无数据</li>');
        }
        else {
            for (var k=0;k<primaryClassification.length;k++){
                primaryClassificationall.push(primaryClassification[k].categoryId)
            }
            for (var i = 0; i < data.data.length; i++) {
                var categoryId = data.data[i].category_id;
                if ($.inArray(categoryId, primaryClassificationall) != -1) {
                    $("#classSet1").append('<li class="clearfix pl-10 mb-5"  style="width: 95%" ><div class="f-l pd-5">' +
                        '<input id="' + data.data[i].category_id + '" onclick="nextbox1(this,'+data.data[i].category_code+',' +data.data[i].category_id + ')" name="classification01" type="checkbox" data-level="'+data.data[i].category_level+'" checked="checked" data-name="'+data.data[i].category_name+'" value="' + data.data[i].category_id + '" class="checkbox" />' +
                        '<label id="' + data.data[i].category_id + 'q" class="pl-10"  onclick="isFirstClick(2,' +data.data[i].category_id + ',this)">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div>' +
                        '</div></li>')
                } else {
                    $("#classSet1").append('<li class="clearfix pl-10 mb-5"  style="width: 95%" ><div class="f-l pd-5">' +
                        '<input id="' + data.data[i].category_id + '" onclick="nextbox1(this,'+data.data[i].category_code+',' +data.data[i].category_id + ')" name="classification01" type="checkbox" data-level="'+data.data[i].category_level+'" data-name="'+data.data[i].category_name+'" value="' + data.data[i].category_id + '" class="checkbox" />' +
                        '<label id="' + data.data[i].category_id + 'q" class="pl-10"  onclick="isFirstClick(2,' +data.data[i].category_id + ',this)">' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div>' +
                        '</div></li>')
                }

            }
        }
    };
    return web.doAjax(root.goodsInter.goods_listCategory, 'post', user_data, succCallBack);
}

function nextbox1(that) {
    var checkeddata={}
    var Val = parseInt(that.value);
    if(that.checked){
        checkeddata={
            "categoryId":Val,
            "floorId":floorManagementid,
            "categoryLevel":$(that).attr("data-level"),
            "categoryName":$(that).attr("data-name")
        }
        primaryClassification.push(checkeddata)
    } else{
        $("#classDiv2").css({
            display: "none"
        });
        for (var i = 0; i < primaryClassification.length; i++) {
            if (primaryClassification[i].categoryId == Val) {
                primaryClassification.splice(i, 1);
                i--;
            }
        }
    }
    goods_listCategory2(2,Val,that.nextElementSibling)//渲染二级类
}
//二级分类
function goods_listCategory2(classNum, parentId, e) {
    var secondaryClassificationall=[]
    console.log(secondaryClassification)
    if(e.previousElementSibling.checked){
        var checkbox = e.previousElementSibling;
        $(".removeEl2").remove();
        $("#classDiv2").css({
            display: "block"
        });
        var user_data = {
            category_id: parentId
        }
        var succCallBack = function (data, status, response) {
            if (data.data.length == 0) {
                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"  style="width: 95%" >无数据</li>');
            }
            else {
                //有数据
                for (var k=0;k<secondaryClassification.length;k++){
                    secondaryClassificationall.push(secondaryClassification[k].categoryId)
                }
                for (var i = 0; i < data.data.length; i++) {
                        var categoryId = data.data[i].category_id;
                        if (checkbox.checked) {
                            if ($.inArray(categoryId, secondaryClassificationall) != -1) {
                                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"  style="width: 95%" ><div class="f-l pd-5" ><input onclick="nextbox2(this,' + data.data[i].category_code + ',' + parentId + ')" name="classification02" type="checkbox" data-level="' + data.data[i].category_level + '" data-name="' + data.data[i].category_name + '" value="' + data.data[i].category_id + '" checked="checked" class="" /><label class="pl-10 secondlevel"  >' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                            } else {
                                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"  style="width: 95%" ><div class="f-l pd-5"><input onclick="nextbox2(this,' + data.data[i].category_code + ',' + parentId + ')"  name="classification02" type="checkbox" data-level="' + data.data[i].category_level + '" data-name="' + data.data[i].category_name + '" value="' + data.data[i].category_id + '"  class="" /><label class="pl-10 secondlevel" >' + data.data[i].category_code + ' ' + data.data[i].category_name + '</label></div></li>')
                            }
                        }
                    }
            }
        };
        return web.doAjax(root.goodsInter.goods_subCategory, 'post', user_data, succCallBack);
    }else {
        var user_data2 = {
            category_id: parentId
        }
        var succCallBack2 = function (data, status, response) {
            for (var h = 0; h < data.data.length; h++) {
                for (var i = 0; i < secondaryClassification.length; i++) {
                    var categoryId = data.data[h].category_id;
                        if (secondaryClassification[i].categoryId == categoryId) {
                            secondaryClassification.splice(i, 1);
                            i--;
                        }
                    }
                }

        };
        return web.doAjax(root.goodsInter.goods_subCategory, 'post', user_data2, succCallBack2);
    }
}

function nextbox2(that,valCode,parentId) {
    var checkeddata={}
    var Val = parseInt(that.value);
    if(that.checked){
        checkeddata={
            "categoryId":Val,
            "floorId":floorManagementid,
            "categoryLevel":$(that).attr("data-level"),
            "categoryName":$(that).attr("data-name")
        }
        if(secondaryClassification.length>14){
            layer.msg("最多选择15个二级分类", {icon: 5, time: 1000});
            that.checked=false
            return false;

        }
        secondaryClassification.push(checkeddata)
    } else{
        for (var i = 0; i < secondaryClassification.length; i++) {
            if (secondaryClassification[i].categoryId == Val) {
                secondaryClassification.splice(i, 1);
                i--;
            }
        }
    }
    console.log(secondaryClassification)
}
function isFirstClick(classNum, parentId, e) {
    goods_listCategory2(classNum, parentId, e)//渲染二级类
}
//上传图片
function addBtn(cen) {
    $(cen).prev().trigger('click');
}
var formData = new FormData();
// 提交上传图片
function getupfilerul(can,e){
    var formData = new FormData();
    formData.append('file',$(can)[0].files[0]);
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            for(var i=0; i<data.length; i++){
                $(can).prev().val(data[0].reletivePath)
                $(can).prev().text(data[0].reletivePath)
            }
            $("#fileUpone").attr('type','text');
            $("#fileUpone").attr('type','file');
            imgoperation=true
            fullPaths=data[0].fullPath
        }
    })
}
// 上传图片返现
function putDataToPage(e,can) {
    //验证
    verificationPicFileType(can)
    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;
                if (width != 232 | height != 550){
                    $.Huimodalalert('图片尺寸限制为：232px*550px',2000);
                    file.value = "";
                    $("#fileUpone").attr('type','text');
                    $("#fileUpone").attr('type','file');
                    return ;
                }else {
                    $(can).parent().prev().children().attr("src", e.target.result);
                    $(can).next().text('更换图片')
                    getupfilerul(can,e)
                }

            };


        }
    }
    formData.append('file', $(can)[0].files[0]);
}
// 图片类型验证
function verificationPicFileType(file) {
    var flag=false;
    var fileTypes = [".jpg", ".png"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('图片格式jpg、png',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}

//删除
function deletepic(can,id) {
          if(imgoperation==true){
            //操作选中图片是=时
            $(can).parent().prev().children().attr("src","" )
              fullPaths=""
        }else {
            $("#pcUrl").attr("src","")
        }
}
//确定
function floorInformation() {
        var floorUrl=""
        if(imgoperation==true){
            floorUrl=fullPaths
        }else {
            floorUrl=$("#pcUrl").attr("src")
        }
        var categoryLists=[]
        for(var a=0;a<primaryClassification.length;a++){
            categoryLists.push(primaryClassification[a])
        }
    for(var b=0;b<secondaryClassification.length;b++){
        categoryLists.push(secondaryClassification[b])
    }
    console.log(categoryLists)
    if(floorUrl==""){
        $.Huimodalalert('请选择图片',2000);
        return false;
    }
    console.log(primaryClassification)
    console.log(secondaryClassification)
    if(primaryClassification==""){
        $.Huimodalalert('请选择一级分类',2000);
        return false;
    }
    if(secondaryClassification==""){
        $.Huimodalalert('请选择二级分类',2000);
        return false;
    }
    $.ajax({
        url:root.sroreinter.addFloorCategoryMsg,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "floorId":floorManagementid,
            "floorUrl":floorUrl,
            "categoryList":categoryLists,
        }),
        success: function (data) {
            if(data.errorCode==0){
                layer.msg('编辑成功', {icon: 6,time:1000});
                setTimeout( function () {
                    location.replace(location.href);
                },1000);
            }else {
                $.Huimodalalert(data.msg,2000);

            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//取消
function floorInforclose() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

/*
关联商品
*/
function floorgoods() {

    $.ajax({
        url:root.sroreinter.findProductByFloorId,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":20,
            "floorId":floorManagementid,
            "skuCode":$("#skuCodes").val()
        }),
        success: function (data) {
            floorgoodslist(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.sroreinter.findProductByFloorId,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":20,
                            "floorId":floorManagementid,
                            "skuCode":$("#skuCodes").val()

                        }),
                        success: function (result) {
                            floorgoodslist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
var dataSource = new Array();
var table;   //table对象
dataSource = [];
function floorgoodslist(data, index){
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组
    if(data !=null && data != ''){
        console.log(data)
        $.each(data.data, function (i, field) {
            var rowData = new Array();
            rowData.push(field.skuName);
            rowData.push(field.spuId);
            rowData.push(field.productStatus);//上下架状态
            rowData.push(field.skuCode);
            rowData.push(field.skuOrder);
            rowData.push(field.id);
            dataSource.push(rowData);

        });
    }
    initDataTablea(dataSource);
    function initDataTablea(dataSource) {
        var dttable = $('#floorgoodstables').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#floorgoodstables").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == 0) {
                            val = '上架'
                        }else  if (val == 1) {
                            val = '下架'
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val='<a onclick="newInformation(2,\''+row[3]+'\',\''+row[4]+'\',\''+row[5]+'\')">编辑</a><a class="ml-10" onclick="deleteFloorProductMsg(\''+row[5]+'\')">删除</a>'
                        return val;
                    },
                    "targets":5
                }


            ]
        });
        //权限控制函数
        power()
    };
}
var pages=""
//新增
function newInformation(val,skuCode,skuOrder,id) {
    $("#floorManagementname").html(floorManagementname)
    if(val==1){
        pages="新增"
        $("#skuCode").val("")
        $("#skuOrder").val("")
    }else if(val==2){
        pages="编辑"
        $("#floorIds").val(id)
        $("#skuCode").val(skuCode)
        $("#skuOrder").val(skuOrder)
    }
    $("#newInformation").modal("show");
}
function addFloorProductMsg() {
    if($("#skuCode").val()==""){
        $.Huimodalalert('请填写SKU编码',2000);
        return false

    }
    if($("#skuOrder").val()==""){
        $.Huimodalalert('请填写展示顺序',2000);
        return false

    }
    if(pages=="编辑"){
        urls=root.sroreinter.updateFloorProductMsg
    }else {
        urls=root.sroreinter.addFloorProductMsg
    }
    $.ajax({
        url:urls,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "id":$("#floorIds").val(),
            "floorId":floorManagementid,
            "skuCode":$("#skuCode").val(),
            "skuOrder":$("#skuOrder").val(),
        }),
        success: function (data) {
            if(data.errorCode==0){
                if(pages=="编辑"){
                    $.Huimodalalert('编辑成功',2000);
                }else {
                    $.Huimodalalert('添加成功',2000);
                }
                $("#newInformation").modal("hide")
                floorgoods()

            }else {
                $.Huimodalalert(data.msg,2000);

            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//取消
function closeFloorProductMsg() {
    $("#newInformation").modal("hide")

}
function deleteFloorProductMsg(id) {
    var curInd = layer.confirm(
        '<span>确定要删除吗？</span>'+'<br/>', {offset:'230px',title:'提示',btn: ['确定', '取消']}, function(index){

            $.ajax({
                url:root.sroreinter.deleteFloorProductMsg,
                dataType: "json",
                type: "post",
                contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                data:{
                    "id":id,
                },
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert('删除成功',2000);
                        floorgoods()

                    }else {
                        $.Huimodalalert(data.msg,2000);

                    }

                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });

            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });

}